package com.frxuexi.shop.view

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.CartBean
import com.frxuexi.lib_base.entity.CartBeanItem
import com.frxuexi.lib_base.entity.CreateOrderReqBean
import com.frxuexi.lib_base.entity.GetPreOrderBean
import com.frxuexi.lib_base.entity.OrderDetail
import com.frxuexi.lib_base.entity.PreOrderReqBean
import com.frxuexi.lib_base.entity.PreOrderRespBean
import com.frxuexi.lib_base.mvi.BaseFragment
import com.frxuexi.lib_base.mvi.RequestType
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.lib_base.room.OrderEntity
import com.frxuexi.lib_base.utils.ArouterManager
import com.frxuexi.shop.R
import com.frxuexi.shop.adapter.CartAdapter
import com.frxuexi.shop.databinding.FragmentCartBinding
import com.frxuexi.shop.intent.CartIntent
import com.frxuexi.shop.viewmodel.CartViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@AndroidEntryPoint
class CartFragment : BaseFragment<FragmentCartBinding,CartIntent,CartViewModel>() {
    override val binding: FragmentCartBinding by lazy { FragmentCartBinding.inflate(layoutInflater) }
    override val vm: CartViewModel by viewModels<CartViewModel>()
    val cartAdapter by lazy { CartAdapter() }
    val list= mutableListOf<CartBeanItem>()
    var position=-1

    var sum=0.0
    override fun initData() {
        lifecycleScope.launch {
           vm.uiState.collect{
               when(it){
                   is UiState.onSuccess<*> ->{
                       when(it.type){
                            RequestType.DEFAULT->{
                                val bean = it.data as CartBean
                                cartAdapter.data.clear()
                                cartAdapter.addData(bean.list)
                                cartAdapter.notifyDataSetChanged()

                                binding.cartNum.setText("购物车（${bean.total}）")
                            }
                           RequestType.UPDATE->{
                                cartAdapter.notifyItemChanged(position)
                           }
                           RequestType.DELETE->{
                               vm.sendIntent(CartIntent.getCarts(1))
                               binding.amountAll.setText("合计：￥0.0")
                           }
                           RequestType.PREORDER->{
                               val bean = it.data as PreOrderRespBean
                               vm.sendIntent(CartIntent.getPreOrder(bean.preOrderNo))
                           }
                           RequestType.GET_PREORDER->{
                               val bean = it.data as GetPreOrderBean
                               /*val reqBean = CreateOrderReqBean(
                                   bean.orderInfoVo.addressId,
                                   bean.orderInfoVo.userCouponId,
                                   bean.orderInfoVo.remark?:"",
                                   "alipay",
                                   "yue",
                                   bean.orderInfoVo.phone,
                                   bean.preOrderNo.toString(),
                                   bean.orderInfoVo.realName,
                                   1,
                                   0,
                                   false
                               )
                               vm.sendIntent(CartIntent.createOrder(reqBean))*/
                               cartAdapter.data.filter { it.isCheck }.forEach {
                                   val entity = OrderEntity(
                                       null,
                                       it.productId,
                                       it.storeName,
                                       it.price.toDouble(),
                                       it.cartNum,
                                       it.image,
                                       1
                                   )
                                   vm.sendIntent(CartIntent.addOrder(entity))
                               }
                           }
                           RequestType.ADD->{
                               Log.i("lr",it.data.toString())
                           }
                           RequestType.ADD_ORDER->{
                               ToastUtils.showLong("下单成功")
                               ArouterManager.nav(requireContext(),"/shop/OrderActivity")
                           }
                           else -> {}
                       }
                   }

                   else -> {}
               }
           }
        }
    }

    override fun initView() {

        binding.rvCar.apply {
            adapter=cartAdapter
            layoutManager=LinearLayoutManager(requireContext())
        }
        vm.sendIntent(CartIntent.getCarts(1))

        binding.cbAll.setOnClickListener {
            //全选反选
            cartAdapter.data.forEach { it.isCheck=binding.cbAll.isChecked }
            cartAdapter.notifyDataSetChanged()

            if(binding.cbAll.isChecked){
                binding.amountAll.setText("合计：￥${cartAdapter.data.sumOf { it.cartNum*it.price.toDouble() }}")
                binding.buyNow.setText("结算(${cartAdapter.data.size})")
            }else{
                binding.amountAll.setText("合计：￥0.0")
                binding.buyNow.setText("结算(0)")
            }
        }

        cartAdapter.addChildClickViewIds(R.id.car_check_box,R.id.car_add,R.id.car_sub)
        cartAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = cartAdapter.data.get(position)
            this.position=position
            when(view.id){
                R.id.car_check_box->{
                    //选项的状态跟着item的状态改变
                    item.isCheck=!item.isCheck
                    cartAdapter.notifyItemChanged(position)
                    binding.cbAll.isChecked=cartAdapter.data.all { it.isCheck }

                    sum=cartAdapter.data.filter { it.isCheck }.sumOf { it.cartNum*it.price.toDouble() }

                    binding.buyNow.setText("结算(${cartAdapter.data.filter { it.isCheck }.count()})")
                }
                R.id.car_add->{
                    item.cartNum=item.cartNum+1
                    if(item.cartNum<=item.stock) {
                        vm.sendIntent(CartIntent.updateCart(item.id, item.cartNum + 1))
                        if(item.isCheck){
                            sum+=item.price.toDouble()

                        }
                    }else{
                        ToastUtils.showLong("没有足够库存了")
                    }
                }
                R.id.car_sub->{
                    if(item.cartNum==1){
                        ToastUtils.showLong("购买数不能小于1")
                    }else{
                        item.cartNum=item.cartNum-1
                        vm.sendIntent(CartIntent.updateCart(item.id,item.cartNum-1))
                        if(item.isCheck){
                            sum-=item.price.toDouble()
                        }
                    }
                }
            }
            binding.amountAll.setText("合计：￥${sum}")
        }

        binding.cartDelete.setOnClickListener {
            val list1 = cartAdapter.data.filter { it.isCheck }.map { it.id }
            vm.sendIntent(CartIntent.deleteCart(list1))
        }


        binding.buyNow.setOnClickListener {
            cartAdapter.data.filter { it.isCheck }.forEach {
                val preOrderBean = PreOrderReqBean(
                    preOrderType = "shoppingCart",
                    productId = it.productId,
                    shoppingCartId = it.id,
                    orderDetails = listOf<OrderDetail>(
                        OrderDetail(preOrderType = "shoppingCart",
                            productId = it.productId,
                            shoppingCartId = it.id)
                    )
                )
                vm.sendIntent(CartIntent.preOrder(preOrderBean))
            }

        }


    }

}